package com.cloud.gateway.handler;

import com.cloud.gateway.bean.ResponseInfo;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;

import java.util.Map;

public class WebErrorHandler extends DefaultErrorWebExceptionHandler {

    public WebErrorHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
        boolean includeStackTrace = this.isIncludeStackTrace(request, MediaType.ALL);
        Map<String, Object> error = this.getErrorAttributes(request, includeStackTrace);
        HttpStatus errorStatus = this.getHttpStatus(error);

        ResponseInfo responseInfo = new ResponseInfo(errorStatus.value());
        if (errorStatus == HttpStatus.NOT_FOUND) {
            responseInfo.setMessage("请求路径不存在");
        } else {
            responseInfo.setMessage("服务器内部错误");
        }
        return ServerResponse.status(HttpStatus.OK).contentType(MediaType.APPLICATION_JSON_UTF8).body(BodyInserters.fromObject(responseInfo)).doOnNext((resp) -> {
            this.logError(request, errorStatus);
        });
    }

}
